package com.ag.hmk.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class HmkUiltDAO extends HibernateDaoSupport {

	private static final Log log = LogFactory.getLog(HmkUiltDAO.class);

	/*
	 * 记录总数
	 */
	public List queryCount(final String hql) throws Exception {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session s) throws HibernateException,
					SQLException {
				Query query = s.createQuery(hql);
				List list = query.list();
				return list;
			}
		});
	}
	
	/*
	 * 分页查询
	 */
	public List queryList(final String hql, final int firstRow, final int maxRow) throws Exception {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session s) throws HibernateException,
					SQLException {
				Query query = s.createQuery(hql);
				query.setFirstResult(firstRow);
				query.setMaxResults(maxRow);
				List list = query.list();
				System.out.println("===================dao==================");
				return list;
			}
		});
	}
	
	/*
	 * hql查询方式
	 */
	public List hqlQuery(final String hql) throws Exception {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session s) throws HibernateException,
					SQLException {
				Query query = s.createQuery(hql);
				List list = query.list();
				return list;
			}
		});
	}
	
	/*
	 * 删除所有短信（by cusID）
	 */
	public void queryUpdate(String sql){
		log.debug("queryUpdate");
		Session session =null;
		Transaction tx = null;
		try {
			//String sql="delete from tb_msg where custom_id='"+cusID+"'";
			session = getHibernateTemplate().getSessionFactory().openSession();
			tx = session.beginTransaction();
			session.createSQLQuery(sql).executeUpdate();
			tx.commit();
			session.close();
			
		} catch (RuntimeException re) {
			log.error("queryUpdate" ,re);
			//session.close();
			throw re;
		}
	}

}
